package com.fxw.mylibrary.util;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.graphics.drawable.DrawableCompat;

/**
 * @author xianwen.fu
 * @version v1.0
 * @Title drawable工具类
 * @Description:
 * @Date 2016/7/19 0019 上午 10:59
 */
public class DrawableUtils {

    /**
     * 改变drawable颜色
     *
     * @param iconResources drawable图标
     * @param color         颜色值
     * @return 改变过后的drawable
     */
    public static Drawable changeDrawableColor(Context context, int iconResources, int color) {
        Drawable icon;
        ColorStateList colorStateList;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            icon = context.getDrawable(iconResources);
        else
            icon = context.getResources().getDrawable(iconResources);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            colorStateList = context.getColorStateList(color);
        else
            colorStateList = context.getResources().getColorStateList(color);

        assert icon != null;
        int mIconSize = icon.getIntrinsicWidth();
        Drawable.ConstantState state = icon.getConstantState();
        icon = DrawableCompat.wrap(state == null ? icon : state.newDrawable()).mutate();
        icon.setBounds(0, 0, mIconSize, mIconSize);
        DrawableCompat.setTintList(icon, colorStateList);
        return icon;
    }
}
